// pages/activity/index/index.js
let app = getApp();
let utilApp = require('../../../../utils/app');
let base = require('../../../../utils/base');
const {
  regeneratorRuntime
} = global
// 获取剩余结束时间戳

Page({
  /**
   * 页面的初始数据 
   */
  data: {
    headerMsg: '',
    pop: false,
    sharePop: false,
    motto: '分享给朋友',
    userInfo: {},
    surplus: 0,
    time: {
      hours: '00',
      minutes: '00',
      seconds: '00'
    },
    uid: 0,
    header: '../../../../image/banner.jpg',
    friendsImg: [],
    friendsLength: 0,
    success: 4,
    itemId: 0,
    phoneNum: 0,
    twoPhoneNum: 0,
    hiddenModal: false,
    formId: '',
  },

  /**
   * 生命周期函数--监听页面加载 
   */
  //  遮罩层显示隐藏 
  popShow: async function(e) {

    let userInfo = wx.getStorageSync('userInfo');
    let addFormId = await utilApp.doPost('User/addFormId', {
      uid: userInfo.uId,
      form_id: e.detail.formId
    })
    this.setData({
      pop: !this.data.pop,
    })
  },
  popHide() {
    this.setData({
      pop: false,
      sharePop: false
    })
  },
  phoneNum(e) {
    this.setData({
      phoneNum: e.detail.value
    })
  },
  twoPhoneNum(e) {
    this.setData({
      twoPhoneNum: e.detail.value
    })
  },
  listenerConfirm: async function() {
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    var myreg = /^[1][0-9][0-9]{9}$/;
    if (!myreg.test(this.data.phoneNum)) {
      utilApp.showModal('提示', '请输入正确的手机号码', '确认', function() {}, function() {}, false)
    } else if (this.data.phoneNum != this.data.twoPhoneNum) {
      utilApp.showModal('提示', '两次号码不一致', '确认', function() {}, function() {}, false)
    } else {
      let getInviter = await utilApp.doPost('User/ajax_bind', {
        openId: userInfo.openId,
        phone: that.data.phoneNum
      });
      if (getInviter.data.status == 1) {
        that.setData({
          hiddenModal: false
        })
        utilApp.showModal('提示', '请前往公众号“猫姐帮你选”,回复数字: 10领取话费', '复制兑换', function() {
          wx.setClipboardData({
            data: '10',
            success: function(res) {
              wx.getClipboardData({
                success: function(res) {
                  wx.showToast({
                    title: '复制成功'
                  })
                }
              })
            }
          })
        }, function() {}, false)
      } else {
        utilApp.showModal('提示', getInviter.data.msg, '确定', function() {}, function() {}, false)
      }
    }
  },
  getBag: async function() {
    let userInfo = wx.getStorageSync('userInfo');
    let uid = userInfo.uId;
    let getInviter = await utilApp.doPost('User/getInviter', {
      uid
    });
    if (getInviter.data.inviter.phone == 0) {
      this.setData({
        hiddenModal: true
      })
    } else {
      utilApp.showModal('提示', '请前往公众号“猫姐帮你选”,回复数字: 10领取话费', '复制兑换', function() {
        wx.setClipboardData({
          data: '10',
          success: function(res) {
            wx.getClipboardData({
              success: function(res) {
                wx.showToast({
                  title: '复制成功'
                })
              }
            })
          }
        })
      }, function() {}, false)
    }
  },

  // 分享到朋友圈
  sharePengYouQuan() {
    this.setData({
      pop: false
    })

    wx.showLoading({
      title: '正在生成海报中',
    })
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    console.log(userInfo.avatarUrl)
    const wxGetImageInfo = utilApp.promisify(wx.getImageInfo)
    async function drawImage() {
      let arr = []
      let getCodeImg = await utilApp.doPost('User/caeateCode', {
        scene: userInfo.uId,
        page: 'pages/activity/combination/index/index'
      });
      console.log(getCodeImg.data)
      let d1 = await wxGetImageInfo({
        src: getCodeImg.data
      })
      let d2 = await wxGetImageInfo({
        src: userInfo.avatarUrl
      })
      arr.push(d2);
      arr.push(d1);
      return arr;
    }
    drawImage().then(function(res) {
      console.log(res)
      const ctx = wx.createCanvasContext('shareCanvas')
      const resWidth = wx.getSystemInfoSync();
      const radio = resWidth.screenWidth / 750;
      // 底图 
      ctx.drawImage('../../../../image/haibao.jpg', 0, 0, 600 * radio, 900 * radio)
      // 二维码
      ctx.drawImage(res[1].path, 200 * radio, 650 * radio, 200 * radio, 200 * radio)
      //  头像 
      ctx.drawImage(res[0].path, 20 * radio, 30 * radio, 80 * radio, 80 * radio)
      ctx.stroke()
      ctx.draw()
      wx.hideLoading()
      that.setData({
        sharePop: true
      })
    })
    // })
  },
  //  保存canvas到手机
  save() {
    wx.showLoading({
      title: '请稍后...',
    });
    let that = this;
    const wxCanvasToTempFilePath = utilApp.promisify(wx.canvasToTempFilePath)
    const wxSaveImageToPhotosAlbum = utilApp.promisify(wx.saveImageToPhotosAlbum)
    wxCanvasToTempFilePath({
      canvasId: 'shareCanvas'
    }, this).then(res => {
      return wxSaveImageToPhotosAlbum({
        filePath: res.tempFilePath
      })
    }).then(res => {
      that.setData({
        sharePop: false
      })
      utilApp.showModal('提示', '已保存到相册,快转发此照片到朋友圈吧', '确定', function() {}, function() {}, false)
      wx.hideLoading();
    }, err => {
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        duration: 2000
      })
    })
  },
  close() {
    this.setData({
      sharePop: false
    })
  },
  gotomy() {
    wx.navigateTo({
      url: '../my/my?id=1'
    })
  },
  onLoad: async function(options) {
    let userInfo = wx.getStorageSync('userInfo');
    let that = this;
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene != userInfo.uId) {
        that.setData({
          uid: scene
        })
        let getFormId = await utilApp.doPost('User/getFormId', {
          uid: scene
        });
        that.setData({
          formId: getFormId.data.form_id
        })
      }
    }

    if (options.uid && options.uid != userInfo.uId) {
      this.setData({
        uid: options.uid
      })
      let getFormId = await utilApp.doPost('User/getFormId', {
        uid: options.uid
      });
      that.setData({
        formId: getFormId.data.form_id
      })
    }

    // 未授权跳转
    let wxGetSetting = utilApp.promisify(wx.getSetting);
    let isUserInfo = await wxGetSetting();
    if (!isUserInfo.authSetting['scope.userInfo'] || !userInfo) {
      if (options.scene) {
        utilApp.isGetUserInfo('../../../authorization/authorization', '../activity/combination/index/index?uid=' + decodeURIComponent(options.scene))
      } else if (options.uid) {
        utilApp.isGetUserInfo('../../../authorization/authorization', '../activity/combination/index/index?uid=' + options.uid)
      } else {
        utilApp.isGetUserInfo('../../../authorization/authorization', '../activity/combination/index/index')
      }
    }
  },
  // 获取用户信息

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function(options) {
    let that = this;
    this.getRemainTime().then(res => {
      (async function() {
        console.log(res.count)
        console.log(res.count)
        console.log(res.count)
        console.log(res.count)
        if (res.remainTime > 0 && res.count <= 30000) {
          setInterval(function() {
            let time = utilApp.leftTimer(res.dueTime * 1000)
            that.setData({
              time
            })
          }, 1000)
          that.setData({
            surplus: base.sum - res.count
          })
          that.createContent(that, 0)
        } else {
          that.setData({
            surplus: 0
          })
          that.createContent(that, 2)
        }
      })()
    })
  },
  /**
   * 封装函数开始
   */

  async getRemainTime() {
    let res = await utilApp.doPost('User/getCount');
    let newTime = (Date.parse(new Date())) / 1000;
    return {
      remainTime: res.data.due_time - newTime,
      dueTime: res.data.due_time,
      count: res.data.count
    };
  },
  // 用户id  是否创建团 ， that, 成功， 是不是我的
  async content(uid, isCreate, that, success, isMy) {
    // 创建新团  或者获取团
    let isSuccess = success || 0;
    let createItem = await utilApp.doPost('User/createItem', {
      uid
    });
    let friends = await utilApp.doPost('User/myItem', {
      uid
    }); 
    if (createItem.data.status == 1) {
      that.setData({
        itemId: createItem.data.item_id
      })
    }

    let getInviter = await utilApp.doPost('User/getInviter', {
      uid
    });
    that.setData({
      friendsImg: friends.data.myItem.friends,
      friendsLength: friends.data.myItem.friends.length,
      header: getInviter.data.inviter.headurl
    })
    // 判断是否在结束时间段内
    if (success == 0) {
      //  活动未结束
      if (isMy) {
        // 我的
        // 判断活动是否有 3个人参与
        if (friends.data.myItem.status == 1) {
          // 有三个人参与
          that.setData({
            success: 1,
            headerMsg: '进度条已完成，快去领话费了',
          })
        } else {
          // 没有三个人参与
          that.setData({
            success: 0,
            headerMsg: '就差一点了，快拉好友来帮忙',
          })
        }
      } else {
        // 好友的
        if (friends.data.myItem.status == 1) {
          // 有三个人参与
          that.setData({
            success: 4,
            headerMsg: '进度条已完成，快去领话费了',
          })
          utilApp.showModal('提示', '该团已满，现在开团参与活动，即可获得奖励', '立即开团', function() {
            that.setData({
              uid: 0
            })
            that.createContent(that, 0)
            utilApp.showModal('开团成功', '点击右下角‘立即召唤’邀请好友吧', '确定', function() {}, function() {}, true)
          }, function() {}, true)
        } else {
          // 没有三个人参与
          that.setData({
            success: 3,
            headerMsg: '快帮' + friends.data.myItem.nickname + '点一下，他就能免费领取到话费了',
          })
        }
      }
    } else {
      // 活动已结束
      // 判断是否是我的页面
      if (isMy) {
        // 我的
        // 判断活动是否有 3个人参与
        if (friends.data.myItem.status == 1) {
          // 有三个人参与
          that.setData({
            success: 1,
            headerMsg: '进度条已完成，快去领话费了',
          })
        } else {
          // 没有三个人参与
          that.setData({
            success: 2,
            headerMsg: ' ',
          })
          utilApp.showModal('提示', '该活动已结束', '确定', function() {

          }, function() {}, true)
        }
      } else {
        // 好友的
        that.setData({
          success: 2,
          headerMsg: ' ',
        })
        utilApp.showModal('抱歉', '该活动已结束', '确定', function() {}, function() {}, true)
      }
    }

  },
  async createContent(that, num) {
    let userInfo = wx.getStorageSync('userInfo');
    // 如果链接不带uid参数
    if (that.data.uid) {
      that.content(that.data.uid, false, that, num, false)
    } else {
      that.content(userInfo.uId, true, that, num, true)
    }
  },


  accept: async function(e) {
    let userInfo = wx.getStorageSync('userInfo');
    let uid = this.data.uid;
    let that = this;
    this.getRemainTime().then(res => {
      (async function() {
        if (res.remainTime < 0 || res.count >= 30000) {
          utilApp.showModal('提示', '活动已结束', '确定', function() {}, function() {}, false)
        } else {
          let addShare = await utilApp.doPost('Share/addShare', {
            uid,
            openId: userInfo.openId,
            item_id: that.data.itemId
          });
          if (addShare.data.status == 1) {
            // 如果当前的团人数 为3 发送模板消息
            if (addShare.data.count == 3) {
              let form_id = that.data.formId;
              console.log('接收fromId======' + form_id)
              let getInviter = await utilApp.doPost('User/getInviter', {
                uid
              });
              let touser = getInviter.data.inviter.openid;
              const formData = {
                "keyword1": {
                  "value": "免费领取10元话费"
                },
                "keyword2": {
                  "value": "恭喜您，已获得三位好友的帮助，点击领取话费吧"
                },
              }
              let SendMsg = await utilApp.doPost('User/sendMsg', {
                touser: touser,
                template_id: 'zCoE-3bbLyL5gwuXdAnpOeuP-Smf00xXGa3eVNdLFkc',
                page: 'pages/activity/combination/index/index',
                form_id: form_id,
                data: JSON.stringify(formData),
              })
              console.log(SendMsg); 
            }
            utilApp.showModal('帮助好友成功', '点击开团参与活动，将获得礼品', '立即开团', function() {
              that.setData({
                uid: 0
              })
              that.createContent(that, 0)
              utilApp.showModal('开团成功', '点击右下角‘立即召唤’邀请好友吧', '确定', function() {}, function() {}, true)
            }, function() {}, true)
          } else {
            console.log(addShare)
            utilApp.showModal('失败', addShare.data.msg, '自己开团', function() {
              that.setData({
                uid: 0
              })
              that.createContent(that, 0)
            }, function() {}, true)
          }
        }
      })()
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },
  gotoActivityList() {
    wx.navigateTo({
      url: '/pages/activityList/activityList',
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */

  onShareAppMessage: function(ops) {
    let that = this;
    let userInfo = wx.getStorageSync('userInfo');
    console.log('转发fromId======' + that.data.formId)
    this.setData({
      pop: false
    })
    if (ops.from === 'button') {
      // 来自页面内转发按钮
      console.log(ops.target)
    }
    return {
      title: '免费领取10元话费',
      path: '/pages/activity/combination/index/index?uid=' + userInfo.uId + '&formId=' + that.data.formId,
      imageUrl: '../../../../image/share.jpg',
      success: function(res) {
        // 转发成功
        wx.showToast({
          title: '转发成功',
        })
      },
      fail: function(res) {
        // 转发失败
        console.log("转发失败:" + JSON.stringify(res));
      }
    }
  },
})